package ylzy.com.yanglezhiyang;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import java.util.HashMap;

import androidx.lifecycle.LifecycleObserver;

/**
 * @author ：create by sean
 * 创建日期：2022/9/24 14
 */
public class SoundPoolUtils implements LifecycleObserver {
    public static SoundPool soundPool = null;
    public static HashMap<Integer, Integer> soundMap = new HashMap<>();
    public static int SOUND_BG = 1;
    public static int SOUND_CLICK = 2;
    public static int SOUND_DISMISS = 3;
    public static int SOUND_FAILED = 4;
    public static int SOUND_SUCCESS = 5;

    public static void initSoundPool(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //设置描述音频流信息的属性
            AudioAttributes abs = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            soundPool = new SoundPool.Builder()
                    .setMaxStreams(10)//同时播放的流的最大数量
                    .setAudioAttributes(abs)
                    .build();
        } else {
            /*
                   1.maxStreams :允许同时播放的流的最大值
                   2.streamType ：音频流的类型描述，在Audiomanager中有种类型声明，游戏应用通常会使用流媒体音乐。
                   3.srcQuality：采样率转化质量,通过方法说明可以知道这个参数没有用
            */
            soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        }

        soundMap.put(SOUND_BG, soundPool.load(context, R.raw.bg, 1));
        soundMap.put(SOUND_CLICK, soundPool.load(context, R.raw.click, 2));
        soundMap.put(SOUND_DISMISS, soundPool.load(context, R.raw.dismiss, 2));
        soundMap.put(SOUND_FAILED, soundPool.load(context, R.raw.failed, 2));
        soundMap.put(SOUND_SUCCESS, soundPool.load(context, R.raw.success, 2));
    }

    public static void play(int id){
        soundPool.play(soundMap.get(id), 1, 1, 0, 0, 1);
    }

    public static void playLoopBG(int id){
        if(soundPool==null || soundMap==null || soundMap.size()==0){
            return;
        }
        soundPool.play(soundMap.get(id), 1, 1, 0, -1, 1);
    }

    public static void onDestroy(){
        soundPool.autoPause();
        soundPool.release();
        soundMap.clear();
    }

    public static void onResume(){
        soundPool.resume(1);
    }

    public static void onPause(){
        soundPool.pause(1);
    }

}
